﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.Data.SqlClient;
using System.Threading;

namespace VPCLoadInfo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DialogResult result = openFileDialog1.ShowDialog();
            if (result == DialogResult.OK) // Test result.
            {
                textBox1.Text = openFileDialog1.FileName.ToString();
            }
            //Console.WriteLine(result); // <-- For debugging use.
        }

        delegate void SetTextCallback(string text);

        private void SetText(string text)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.textBox1.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.richTextBox1.Text = text;
            }
        }

        private void Import()
        {
            string line;
            string[] lines;
            string[] delimitador = { "\t" };
            int cont = 1;
            int totalInsert = 0;
            List<String> myList = new List<string>();
            Int64 total = 0;
            //SetText("Calculando Total de Registros... ");
            richTextBox1.Text = "Calculando Total de Registros... ";

            //richTextBox1.Refresh();
            System.IO.StreamReader file = new System.IO.StreamReader(openFileDialog1.FileName.ToString());

            try
            {
                line = file.ReadLine();
                if (!line.Contains("No.	Data		Time		Type			In		Out			Latitude			Longitude			Speed			Flag")) {
                    throw new Exception();
                }
            }
            catch (Exception ex) {
                MessageBox.Show("El archivo es inválido, seleccione el archivo TXT del VPC");
                richTextBox1.Text = "El archivo es inválido, seleccione el archivo TXT del VPC";
                button2.Text = "Importar Archivo";
                button1.Enabled = true;
                return;
            }

            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = ConfigurationSettings.AppSettings["ConnectionString"];

            conn.Open();

            SqlCommand command = new SqlCommand();

            command.Connection = conn;

            string commandText = string.Empty;



            while ((line = file.ReadLine()) != null)
            {
                myList.Add(line);
            }

            total = myList.Count;

            for (cont = 0; cont < total; cont++)
            {
                line = myList[cont].ToString();
                lines = line.Split(delimitador, StringSplitOptions.RemoveEmptyEntries);
                commandText = string.Empty;

                try
                {
                    //SetText("Procesando Registros... " + cont + " de " + total + " ( " + cont * 100 / total + " % )");
                    richTextBox1.Text = "Procesando Registros... " + cont + " de " + total + " ( " + cont * 100 / total + " % )  --  Registros Ingresados: " + totalInsert;
                    //richTextBox1.Refresh();

                    commandText = "Insert into VPCRecordLs(s_Device_IP, n_Record_Type, n_Record_Date, n_Record_InNum, n_Record_OutNum, n_Record_In, n_Record_Out, str_Latitude, str_Longitude, str_Speed, str_Type) Values(";
                    commandText += "'00000090d8e4'"; //Device_IP

                    // Record_Type
                    if (lines[3].ToUpper() == "CH1 IN")
                        commandText += ", 1";
                    if (lines[3].ToUpper() == "CH1 OUT")
                        commandText += ", 2";
                    if (lines[3].ToUpper() == "RESETCOUN")
                        commandText += ", 3";
                    if (lines[3].ToUpper() == "CH2 IN")
                        commandText += ", 5";
                    if (lines[3].ToUpper() == "CH2 OUT")
                        commandText += ", 6";
                    if (lines[3].ToUpper() == "CH1 COVERED")
                        commandText += ", 7";
                    if (lines[3].ToUpper() == "CH1 UNCOVERED")
                        commandText += ", 8";
                    if (lines[3].ToUpper() == "CH2 COVERED")
                        commandText += ", 9";
                    if (lines[3].ToUpper() == "CH2 UNCOVERED")
                        commandText += ", 10";
                    if (lines[3].ToUpper() == "CH1 OPEN DOOR")
                        commandText += ", 11";
                    if (lines[3].ToUpper() == "CH1 CLOSE DOOR")
                        commandText += ", 12";
                    if (lines[3].ToUpper() == "CH2 OPEN DOOR")
                        commandText += ", 13";
                    if (lines[3].ToUpper() == "CH2 CLOSE DOOR")
                        commandText += ", 14";
                    if (lines[3].ToUpper() == "RESTARTVPC" || lines[3].ToUpper() == "ABNORMAL")
                        commandText += ", -1";

                    commandText += ", '" + lines[1] + " " + lines[2] + "'";  //Record_Date
                    commandText += ", " + lines[4]; //Record_InNum
                    commandText += ", " + lines[5]; //Record_OutNum

                    //Record_In
                    if (lines[3].ToUpper() == "CH2 IN" || lines[3].ToUpper() == "CH1 IN")
                        commandText += ", 1";
                    else
                        commandText += ", 0";

                    //Record_Out
                    if (lines[3].ToUpper() == "CH2 OUT" || lines[3].ToUpper() == "CH1 OUT")
                        commandText += ", 1";
                    else
                        commandText += ", 0";

                    commandText += ", " + lines[6]; //Latitude
                    commandText += ", " + lines[7]; //Longitude
                    commandText += ", " + lines[8];//Speed
                    commandText += ", 'M')"; //Type
                    command.CommandText = commandText;

                    if (button2.Text == "Importar Archivo")
                        break;

                    if (lines[3].ToUpper() != "RESTARTVPC")
                    {
                        command.ExecuteNonQuery();
                        totalInsert++;
                    }

                }
                catch (Exception ex)
                {
                    if (ex.Message.Contains("PRIMARY KEY"))
                    {
                        //
                    }
                    else
                        MessageBox.Show(ex.Message);
                }
            }

            conn.Close();
            if (button2.Text == "Importar Archivo")
                richTextBox1.Text = "Proceso Cancelado... Total de Registros Procesados " + cont + " de " + total + "  --  Registros Ingresados: " + totalInsert;
            else
                richTextBox1.Text = "Proceso Finalizado... Total de Registros " + total + "  --  Registros Ingresados: " + totalInsert;
            button1.Enabled = true;
            //SetText("Proceso Finalizado... Total de Registros " + total);

            //button2.Enabled = true;
            button2.Text = "Importar Archivo";
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (button2.Text == "Importar Archivo")
            {
                Button.CheckForIllegalCrossThreadCalls = false;
                RichTextBox.CheckForIllegalCrossThreadCalls = false;

                if (string.IsNullOrEmpty(textBox1.Text))
                {
                    MessageBox.Show("Debe seleccionar un archivo");
                    return;
                }

                //button2.Enabled = false;
                button2.Text = "Cancelar";
                button1.Enabled = false;

                Thread oThread = new Thread(new ThreadStart(this.Import));
                oThread.Start();
                //Import();
            }
            else
                button2.Text = "Importar Archivo";
        }

    }
}
